package pers.qianyu.month_202011.date_20201121;

import java.util.*;

/**
 * 652. 寻找重复的子树
 * https://leetcode-cn.com/problems/find-duplicate-subtrees/
 *
 * @author mizzle rain
 * @date 2020-11-21 20:04
 */
public class FindDuplicateSubtrees {
    private HashMap<String, Integer> map = new HashMap<>();
    private List<TreeNode> res = new ArrayList<>();

    public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
        if (root == null) {
            return new ArrayList<>();
        }
        recur(root);
        return res;
    }

    private String recur(TreeNode root) {
        if (root == null) {
            return "#";
        }
        String left = recur(root.left);
        String right = recur(root.right);
        String s = left + "," + right + "," + root.val;
        Integer num = map.getOrDefault(s, 0);
        if (num == 1) {
            res.add(root);
        }
        map.put(s, num + 1);
        return s;
    }

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
